import DataStore from 'lowdb';
import FileSync from 'lowdb/adapters/FileSync';
import LodashId from 'lodash-id';
import path from 'path';
import fs from 'fs-extra';
import { app, remote } from 'electron';
import pkg from '../../package';

if (process.env.NODE_ENV !== 'development') {
  global.__static = path.join(__dirname, '/static')
    .replace(/\\/g, '\\\\');
}
if (process.env.DEBUG_ENV === 'debug') {
  global.__static = path.join(__dirname, '../../static')
    .replace(/\\/g, '\\\\');
}

const APP = process.type === 'renderer' ? remote.app : app;
const STORE_PATH = APP.getPath('userData');

if (process.type !== 'renderer') {
  if (!fs.pathExistsSync(STORE_PATH)) {
    fs.mkdirpSync(STORE_PATH);
  }
}

const adapter = new FileSync(path.join(STORE_PATH, '/db.json'));

const db = DataStore(adapter);
db._.mixin(LodashId);

if (!db.has('uploaded')
  .value()) {
  db.set('uploaded', [])
    .write();
}

if (!db.has('settings.shortKey')
  .value()) {
  db.set('settings.shortKey', {
    upload: 'CommandOrControl+Shift+P'
  })
    .write();
}

if (!db.has('appInfo')
  .value()) {
  const appInfo = {
    version: pkg.version,
    author: pkg.author,
    name: pkg.name
  };
  db.read()
    .set('appInfo', appInfo)
    .write();
}

export default db;
